package com.ruoyi.record.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.basic.domain.BasicUser;
import com.ruoyi.basic.mapper.BasicUserMapper;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.record.domain.RecordSalaryContent;
import com.ruoyi.record.domain.RecordWage;
import com.ruoyi.record.mapper.RecordSalaryContentMapper;
import com.ruoyi.record.mapper.RecordWageMapper;
import com.ruoyi.record.service.IRecordSalaryContentService;
import com.ruoyi.record.service.IRecordWageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 工资详情Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-02-12
 */
@Service
public class RecordWageServiceImpl extends ServiceImpl<RecordWageMapper, RecordWage> implements IRecordWageService
{
    @Autowired
    private BasicUserMapper basicUserMapper;

    /**
     * 查询档案工资详情
     * 
     * @param wageId 档案工资主键
     * @return 档案工资详情
     */
    @Override
    public RecordWage selectRecordWageByWageId(Long wageId)
    {
        return baseMapper.selectRecordWageByWageId(wageId);
    }

    /**
     * 查询档案工资列表
     * 
     * @param recordWage 档案工资
     * @return 档案工资详情
     */
    @Override
    public List<RecordWage> selectRecordWageList(RecordWage recordWage)
    {
        return baseMapper.selectRecordWageList(recordWage);
    }

    /**
     * 新增档案工资
     * 
     * @param recordWage 档案工资
     * @return 结果
     */
    @Override
    public int insertRecordWage(RecordWage recordWage)
    {
        recordWage.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(recordWage);
    }

    /**
     * 修改档案工资
     * 
     * @param recordWage 档案工资详情
     * @return 结果
     */
    @Override
    public int updateRecordWage(RecordWage recordWage)
    {
        recordWage.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(recordWage);
    }

    /**
     * 批量删除档案工资
     * 
     * @param wageIds 需要删除的档案工资主键
     * @return 结果
     */
    @Override
    public int deleteRecordWageByWageIds(String wageIds)
    {
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(wageIds)));
    }

    /**
     * 删除档案工资
     * 
     * @param wageId 档案工资主键
     * @return 结果
     */
    @Override
    public int deleteRecordWageByWageId(Long wageId)
    {
        return baseMapper.deleteById(wageId);
    }

    /**
     * 导入档案工资
     *
     * @param recordWageList 档案工资列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importRecordWage(List<RecordWage> recordWageList, boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(recordWageList) || recordWageList.size() == 0)
        {
            throw new ServiceException("导入员工档案工资数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 2;
        String REGEX_LOCALE_ENGLISH = "^[a-zA-Z]{3}\\s[a-zA-Z]{3}\\s\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\s[A-Z]{3}\\s\\d{4}$";
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (RecordWage recordWage : recordWageList)
        {
            try
            {
                if(StringUtils.isEmpty(recordWage.getIdCard())){
                    continue;
                }
                if(recordWage.getSalaryType().equals("在职职工")){
                    recordWage.setSalaryType("1");
                }else if(recordWage.getSalaryType().equals("退休职工")){
                    recordWage.setSalaryType("2");
                }else if(recordWage.getSalaryType().equals("铁路退休")){
                    recordWage.setSalaryType("3");
                }else if(recordWage.getSalaryType().equals("临时工")){
                    recordWage.setSalaryType("4");
                }
                //验证用户是否存在
                BasicUser basicUser = basicUserMapper.selectOne(new LambdaQueryWrapper<BasicUser>().eq(BasicUser::getIdCard, recordWage.getIdCard()));
                if(StringUtils.isNull(basicUser)) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + row + "行导入失败，员工 " + recordWage.getUserName() + " 不存在");
                    continue;
                }
                recordWage.setUserId(basicUser.getId());

                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);

                if(StringUtils.isNotEmpty(recordWage.getWageTime()) && recordWage.getWageTime().matches(REGEX_LOCALE_ENGLISH)) {
                    Date wageTime = dateFormat.parse(recordWage.getWageTime());
                    recordWage.setWageTime(DateUtils.parseDateToStr("yyyy-MM-dd", wageTime));
                }

                recordWage.setCreateBy(operName);
                this.insertRecordWage(recordWage);
                successNum++;
                successMsg.append("<br/>" + successNum + "、第" + row + " 行档案工资信息导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、第" + row + " 行工资信息导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            finally {
                row++;
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
